class Weighter:
    def __init__(self, weight):
        self.weight = weight
        return
    
    def getDigitsIndex(self, attributeList):
        indexList = []
        for i in xrange(len(attributeList)):
            if attributeList[i].isdigit():
                indexList.append(i)
        return indexList
    
    def addWeight(self, originDataDict, targetIndexList):
        for key in originDataDict.keys():
            if type(key) == int and (key-1) in targetIndexList:
                originDataDict[key] *= self.weight
        return
    
    def getLineDataDict(self, line):
        dataDict = {}
        elements = line.split()
        dataDict['class'] = elements[0]
        for kvStr in elements[1:]:
            kvTuple = kvStr.split(':')
            k = int(kvTuple[0])
            v = float(kvTuple[1])
            dataDict[k] = v
        return dataDict
    
    def assembleDictToLine(self, lineDataDict):
        elementList = []
        elementList.append(str(lineDataDict['class']))
        for k in sorted(lineDataDict):
            elementList.append("%s:%s"%(k,lineDataDict[k]))
        return ' '.join(elementList)
    
    def convertLine(self, srcLine, targetIndexList):
        di = self.getLineDataDict(srcLine)
        self.addWeight(di,targetIndexList)
        resultLine = self.assembleDictToLine(di)
        return resultLine
        
    def convertFile(self, filename, outputFilename):
        
        try:
            attrList = open(filename+'-words.txt','rU').read().split()
            targetIndexList = self.getDigitsIndex(attrList)
            dataLines = open(filename,'rU')
            out = open(outputFilename,'w+')
            for line in dataLines:
                out.write(self.convertLine(line, targetIndexList))
        finally:
            dataLines.close()
            out.close()
            
        
if __name__=='__main__':
    
    filename = '../test_M09400.dat'
    outputFilename = filename+'.weighted'
    wt = Weighter(2.0)
    wt.convertFile(filename, outputFilename)